package com.fengpanlong.service;

import java.util.List;

import javax.servlet.http.HttpServletRequest;

import com.fengpanlong.dao.MessageDao;
import com.fengpanlong.entity.Employee;
import com.fengpanlong.entity.EmployeeProject;
import com.fengpanlong.entity.Message;
import com.fengpanlong.entity.Project;
import com.fengpanlong.util.StringUtil;
import com.fengpanlong.web.listener.MessageStream;

public class MessageService {
	/**
	 * 查找工程的信息流
	 * @param projectId 工程id
	 * @return
	 */
	public static List<Message> findMessagesByProjectId(String projectId) {
		MessageDao md = new MessageDao();
		return md.findMessagesByProjectId(projectId);
	}
	/**
	 * 得到message对象
	 * @param request 其中必须能得到employee和project对象
	 * @return
	 */
	public static Message getMessage(HttpServletRequest request, String content, String createtime) {
		Employee employee = null;
		Project project = null;
		employee = (Employee) request.getSession().getAttribute("employee");
		project = (Project) request.getAttribute("project");
		if(employee == null || project == null) {
			EmployeeProject ep = (EmployeeProject)request.getSession().getAttribute("ep");
			employee = ep.getEmployee();
			project = ep.getProject();
		}
		Message message = new Message();
		message.setId(StringUtil.getId());
		content = employee.getUsername() + "于" + createtime +  " " + content;
		message.setContent(content);
		message.setCreatetime(createtime);
		message.setEmployeeId(employee.getId());
		message.setProjectId(project.getId());
		return message;
	}
	/**
	 * 发送消息
	 * @param request
	 * @param content
	 * @return 
	 */
	public static Message sendMessage(HttpServletRequest request, String content) {
		Message message = MessageService.getMessage(request, content, StringUtil.formateTime());
		MessageStream messageStream = new MessageStream(message);
		request.getSession().setAttribute("messageStream", messageStream);
		return message;
	}
	/**
	 * 发送创建类消息
	 * @param request
	 * @param content
	 */
	public static void sendMessage(HttpServletRequest request, String content,String createtime) {
		Message message = MessageService.getMessage(request, content, createtime);
		MessageStream messageStream = new MessageStream(message);
		request.getSession().setAttribute("messageStream", messageStream);
	}
}
